<template>
  <div class="login-container flx-center">
    <div class="login-box">
      <div class="login-left">
        <div class="title">高效记录生活</div>
        <div class="sub">轻松收集，有效整理</div>
        <img src="../../assets/login.png" alt="" />
      </div>

      <div class="login-form">
        <div class="login-logo">
          <img class="login-icon" src="../../assets/logo.png" alt="" />
          <p class="logo-text">欢迎登录</p>
        </div>
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          size="large"
        >
          <el-form-item prop="username">
            <el-input
              :prefix-icon="User"
              v-model.trim="loginForm.username"
              placeholder="用户名"
            >
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              type="password"
              show-password
              v-model.trim="loginForm.password"
              placeholder="密码"
            >
            </el-input>
          </el-form-item>
        </el-form>

        <div class="login-btn">
          <el-button
            :icon="CircleClose"
            round
            @click="resetForm(loginFormRef)"
            size="large"
          >
            重置
          </el-button>
          <el-button
            round
            size="large"
            type="primary"
            :loading="loading"
            :icon="UserFilled"
            @click="login(loginFormRef)"
          >
            登录
          </el-button>
        </div>
        <!-- <el-divider>其他方式登录 </el-divider>
        <OtherLogin></OtherLogin> -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useStore } from "vuex"; // 引入useStore 方法
import { ElMessage } from "element-plus";
import { CircleClose, UserFilled, Lock, User } from "@element-plus/icons-vue";
import { Base64 } from "js-base64";
import OtherLogin from "./components/otherLogin.vue";

const loginFormRef = ref();
const loading = ref(false);
const loginForm = reactive({
  username: import.meta.env.DEV ? "8888" : "",
  password: import.meta.env.DEV ? "123123" : "",
  socialCodeValid: true,
});
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
});

const globalStore = useStore(); // 该方法用于返回store 实例

const login = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      loading.value = true;
      console.log(globalStore);
      if (loginForm.socialCodeValid) {
        let password = Base64.encode(loginForm.password); // base64加密
        setCookie(loginForm.username, password, 7);
      } else {
        setCookie("", "", -1);
      }
      globalStore.dispatch("user/login", loginForm);
      setTimeout(() => {
        loading.value = false;
      }, 1000);
    } else {
      console.log("error submit!");
      loading.value = false;
      return false;
    }
  });
};

const setCookie = (userId, password, days) => {
  let date = new Date(); // 获取时间
  date.setTime(date.getTime() + 24 * 60 * 60 * 1000 * days); // 保存的天数
  // 字符串拼接cookie
  window.document.cookie =
    "userId" + "=" + userId + ";path=/;expires=" + date.toGMTString();
  window.document.cookie =
    "password" + "=" + password + ";path=/;expires=" + date.toGMTString();
};

// 读取cookie 将用户名和密码回显到input框中
// const getCookie = () => {
//   if (document.cookie.length > 0) {
//     let arr = document.cookie.split("; "); //分割成一个个独立的“key=value”的形式
//     for (let i = 0; i < arr.length; i++) {
//       let arr2 = arr[i].split("="); // 再次切割，arr2[0]为key值，arr2[1]为对应的value
//       if (arr2[0] === "userId") {
//         loginForm.username = arr2[1];
//       } else if (arr2[0] === "password") {
//         loginForm.password = Base64.decode(arr2[1]); // base64解密
//         loginForm.socialCodeValid = true;
//       }
//     }
//   }
// };

const resetForm = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  ElMessage.success("密码重置成功");
};

// onMounted(() => {
//   //绑定监听事件
//   window.addEventListener("keydown", keyDown);
// });

// onUnmounted(() => {
//   //销毁事件
//   window.removeEventListener("keydown", keyDown, false);
// });
</script>

<style scoped lang="scss" src="./index.scss"></style>
